//
//  UIImage+Extension.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import SDWebImage

extension UIImage {
    
    static var clear: UIImage? {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        defer {
            UIGraphicsEndImageContext()
        }
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    
    class func imageWithColor(_ color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    @discardableResult
    func writeToFileName(name: String) -> String {
        let cacheDirectoryPath = NSHomeDirectory() + "/Library/Caches/camera/"
        if !FileManager.default.fileExists(atPath: cacheDirectoryPath) {
            try? FileManager.default.createDirectory(atPath: cacheDirectoryPath, withIntermediateDirectories: true, attributes: nil)
        }
        let filePath = cacheDirectoryPath + name
        try? self.pngData()?.write(to: URL.init(fileURLWithPath: filePath))
        return filePath
    }
}

extension UIImageView {
    
    func setImageWith(contentsOfFile: String) {
        let image = UIImage.init(contentsOfFile: contentsOfFile)
        self.image = image
    }
    
}
